package com.auxgroup.smarthome.controller;

import cn.apiclub.captcha.Captcha;
import com.auxgroup.smarthome.captcha.CaptchaConstant;
import com.auxgroup.smarthome.captcha.CaptchaUtils;
import com.auxgroup.smarthome.consant.UpmsRedisKeyManage;
import com.auxgroup.smarthome.filter.annotation.PermissionFilter;
import com.auxgroup.smarthome.utils.EncryptionUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * Created by kevinchen on 2017/2/24.
 */
@Api( tags = "系统登录")
@RestController
public class CaptchaController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "getcaptcha")//, produces = MediaType.IMAGE_PNG_VALUE
    @PermissionFilter(filter = true)
    public String getCaptcha(HttpServletResponse response) {
        //生成验证码
        Captcha captcha = CaptchaUtils.getCaptcha();
        //将验证码以<key,value>形式缓存到redis
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(uuid, captcha.getAnswer(), CaptchaConstant.captchaExpires, TimeUnit.SECONDS);
        //将验证码key，及验证码的图片返回
        Cookie cookie = new Cookie("CaptchaCode",uuid);
        response.addCookie(cookie);
        byte[] bytes = CaptchaUtils.getCaptchaStream(captcha);
        return EncryptionUtils.base64Encode(bytes.toString());
    }

    @GetMapping(value = "get-picture-captcha", produces = MediaType.IMAGE_PNG_VALUE)//, produces = MediaType.IMAGE_PNG_VALUE
    @PermissionFilter(filter = true)
    public void getPictureCaptcha(HttpServletResponse response) throws IOException {
        //发送给浏览器
        response.setContentType("image/jpeg");
        //发头控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        //生成验证码
        Captcha captcha = CaptchaUtils.getCaptcha();
        //将验证码以<key,value>形式缓存到redis
        String redisKey = UpmsRedisKeyManage.CAPTCHA_REDIS_PREFIX + captcha.getAnswer();
        redisTemplate.opsForValue().set(redisKey, captcha.getAnswer(), CaptchaConstant.captchaExpires, TimeUnit.SECONDS);
        ImageIO.write(captcha.getImage(), "png", response.getOutputStream());
    }

}
